package cn.js189.uqc.service.impl;

import cn.js189.common.util.StringUtils;
import cn.js189.uqc.mapper.PubAddressIpMapper;
import cn.js189.uqc.redis.RedisOperation;
import lombok.extern.slf4j.Slf4j;
import cn.js189.uqc.service.PubAddressIpervice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;


@Slf4j
@Service
public class PubAddressIpImpl implements PubAddressIpervice {

    /**
     * 测试
     */
    private static final String TEST = "_test";

    /**
     * 生产
     */
    private static final String PRO = "_pro";

    /**
     * 头部测试号码
     */
    private static final String TESTNBR = "testLoginNbr";

    @Resource
    private PubAddressIpMapper pubAddressIpMapper;

    @Resource
    private RedisOperation redisOperation;

    /**
     * 获取调用地址
     */
    @Override
    public String getActionUrl(String addreCode, String loginNbr) {
        log.info("获取调用地址,调用addreCode:{},head--loginNbr:{}",addreCode,loginNbr);
        //更具入参head信息判断调用测试地址或者生产地址
        String url = null;
        if(StringUtils.isBlank(loginNbr)){
            //缓存获取地址
            url = handleCache(addreCode+PRO);
        }else{
            //缓存中获取测试号码
            String testLoginNbr = redisOperation.getForString(TESTNBR);
            if (testLoginNbr.contains(loginNbr)) {
                //缓存中包含 查询测试地址
                url = handleCache(addreCode+TEST);
            } else {
                String testLoginNbrNew = pubAddressIpMapper.selectSwitchInfo();
                if (testLoginNbrNew.contains(loginNbr)) {
                    url = handleCache(addreCode+TEST);
                    //更新缓存信息
                    redisOperation.setForString(TESTNBR,testLoginNbrNew);
                }else{
                    url = handleCache(addreCode+PRO);
                }
            }
        }
        return url;
    }


    /**
     * 处理缓存中地址信息
     */
    public String handleCache(String addreCode){
        log.info("handleCache--查询缓存中信息:{}",addreCode);
        String url = null;
        //缓存获取地址
        url = redisOperation.getForString(addreCode);
        if(StringUtils.isBlank(url)){
            url = pubAddressIpMapper.getActionUrl(addreCode);
            redisOperation.setForString(addreCode,url);
        }
        return url;
    }


}
